// useContext相当vue的inject
import React, { useContext, useState } from 'react';
import { AppContext } from './test2';

const Text22 = ()=>{
    const [user, setUser] = useState({
        name: '',
        age: '',
    });
    
    const changeUser = (e, type)=>{
        let val = e.target.value;
        if(type === 1){
            setUser({
                ...user,
                name: val
            })
        }else{
            setUser({
                ...user,
                age: val
            })
        }
    }

    // useContext 相当于使用 vue的inject,使用隔代组件共享的属性或方法
    const {demoList, setDemoList, logTest} = useContext(AppContext);

    const saveUser = ()=>{
        const item = {
            ...user
        };
        setDemoList([ ...demoList, item ]);
        logTest();  // 父组件的方法
    }

    return <div>
        
        <div className='demo_box' style={{margin:'20px'}}>
            {/* 双向绑定 */}
            <p>
                姓名: {user.name}
                <input className='ipt' type="text" value={user.name} onChange={(e)=>{changeUser(e, 1)}}/>
            </p>
            <p>
                性别: {user.age}
                <input className='ipt' type="text" value={user.age} onChange={(e)=>{changeUser(e, 2)}}/>
            </p>
            <p>
                <button onClick={ saveUser }>保存</button>
            </p>
        </div>
    </div>
}

export default Text22;

